<script lang="ts" setup>
import { appModel, ILogin } from '@/api/app';
import { FormConfig } from '@/components/Form/types';
import { NInput, useMessage } from 'naive-ui';
import { reactive, ref, unref } from 'vue';
import jsCookie from 'js-cookie';
import { useRouter } from 'vue-router';

const router = useRouter();
const message = useMessage();

if(jsCookie.get('Authorization')) {
  router.push('/home');
}

const loginData = reactive<ILogin>({
  username: '',
  password: ''
});

const config: FormConfig<typeof loginData>[] = [
  {
    type: 'component',
    label: '账号:',
    component: NInput,
    key: 'username',
    span: 24,
    itemProps: {
      rule: [
        { validator(rule, value) {
          if(!value) {
            return new Error('请输入账号！');
          }
          return true;
        } }
      ]
    }
  },
  {
    type: 'component',
    label: '密码:',
    component: NInput,
    key: 'password',
    span: 24,
    props: {
      type: 'password'
    },
    itemProps: {
      rule: [
        { validator(rule, value) {
          if(!value) {
            return new Error('请输入密码！');
          }
          return true;
        } }
      ]
    }
  },
  {
    type: 'slot',
    slotName: 'submit',
    span: 24,
    itemProps: {
      showLabel: false
    }
  }
];

const loginForm = ref();
async function submit() {
  await loginForm.value.validate().catch(() => {
    window.$message?.error('信息未完善');
    return Promise.reject(false);
  });
  const params = {
    ...unref(loginData)
  };
  await appModel.login(params).catch((err) => {
    message.error(err.data.message);
    return Promise.reject();
  });
  router.push({ path: '/home' });
}

</script>

<template>
  <div class="h-screen flex justify-center items-center flex-col">
    <div class="text-42px mb-88px">图书管理系统</div>
    <div
      class="w-280px"
    >
      <Form
        ref="loginForm"
        v-model:data="loginData"
        :config="config"
        label-placement="left"
        :grid-props="{ 'y-gap': '0px', 'x-gap': '0px' }"
      >
        <template #submit>
          <div class="flex justify-end">
            <NButtonGroup>
              <NButton @click="submit">
                登录
              </NButton>
            </NButtonGroup>
          </div>
        </template>
      </Form>
    </div>
  </div>
</template>
